package com.sidecar.service.log.web;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;

import com.sidecar.common.dto.search.SearchRequest;
import com.sidecar.common.dto.vo.base.ResponseData;
import com.sidecar.common.dto.vo.log.request.StatusChangeLogReq;
import com.sidecar.service.log.entity.StatusChangeLog;
import com.sidecar.service.log.repository.StatusChangeLogRepository;

import reactor.core.publisher.Mono;

@Component
public class StatusChangeLogController {

    @Resource
    StatusChangeLogRepository statusChangeLogRepository;

    public Mono<ServerResponse> create(ServerRequest req) {
        if (req == null) {
            return ServerResponse.badRequest().body(Mono.justOrEmpty(ResponseData.failure()), ResponseData.class);
        }
        StatusChangeLog log = new StatusChangeLog();
        BeanUtils.copyProperties(req.bodyToMono(StatusChangeLogReq.class).block(), log);
        statusChangeLogRepository.insert(log);
        return ServerResponse.ok().body(Mono.justOrEmpty(ResponseData.failure()), ResponseData.class);
    }

    public Mono<ServerResponse> search(ServerRequest req) {
        SearchRequest request = req.bodyToMono(SearchRequest.class).block();
        if (request == null) {
            return ServerResponse.badRequest().body(Mono.justOrEmpty(ResponseData.failure()), ResponseData.class);
        }
        PageRequest pr = PageRequest.of(request.getPageNo(), request.getPageSize());
        StatusChangeLog log = new StatusChangeLog();
        Example<StatusChangeLog> ex = Example.of(log);
        return ServerResponse.ok().body(
                Mono.justOrEmpty(statusChangeLogRepository.findAll(ex).collectList().block()),
                List.class);
    }
}
